package com.chinawayltd.ews.sample.taskCenter;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class TaskProducerJobManager implements ApplicationListener<ContextRefreshedEvent> {
	
	private Logger logger = LoggerFactory.getLogger(TaskProducerJobManager.class);
	
	private Scheduler scheduler;

	public Scheduler getScheduler() {
		return scheduler;
	}

	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(event.getApplicationContext().getParent()==null){
			this.init();
		}
	}

	private void init() {
		try {
			//初始化定时器工厂
			SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
			scheduler = schedFact.getScheduler();
			scheduler.start();
			//启动任务管理定时任务,每一分钟执行一次
			this.startDbScanJob();
		} catch (SchedulerException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	private void startDbScanJob() throws SchedulerException {
		JobKey jobKey = new JobKey("DB_SCAN", "SYS_JOBS");
		TriggerKey tKey = new TriggerKey("DB_SCAN", "SYS_JOBS");
		JobDetail job = JobBuilder.newJob(TaskProducerJob.class)
				.withIdentity(jobKey).build();
		this.scheduler.unscheduleJob(tKey);
		SimpleTrigger trigger = newTrigger()
				.withIdentity("DB_SCAN", "SYS_JOBS")
				.startAt(new Date())
				.withSchedule(
						SimpleScheduleBuilder.simpleSchedule()
								.withIntervalInSeconds(60).repeatForever())
				.build();
//		CronTriggerImpl trigger = (CronTriggerImpl) newTrigger()
//				.withIdentity("DB_SCAN", "SYS_JOBS")
//				.startAt(new Date()).withSchedule(cronSchedule("30 0/1 * * * ?")).forJob(job)
//				.build();
		scheduler.scheduleJob(job, trigger);
	}
	
	/**
	 * 清理job线程
	 * 
	 * @throws SchedulerException
	 * @throws InterruptedException
	 */
	public void destory() throws SchedulerException, InterruptedException {
		if (this.scheduler != null) {
			this.scheduler.shutdown();
			Thread.sleep(1000);
		}
	}
}
